const { Schema } = require('koishi')

/**
 * @description 剑网三副本信息查询插件
 */
class Jx3DungeonPlugin {
  /**
   * @param {object} ctx - Koishi上下文
   * @param {object} config - 插件配置
   */
  constructor(ctx, config) {
    this.ctx = ctx
    this.config = config
    
    // 获取API服务
    this.jx3Api = ctx.jx3Api
    if (!this.jx3Api) {
      throw new Error('请先安装并配置jx3-api插件')
    }
    
    this.registerCommands()
  }
  
  /**
   * @description 注册命令
   */
  registerCommands() {
    const { ctx } = this
    
    // 副本信息查询
    ctx.command('jx3.副本 <dungeonName>', '查询副本详细信息')
      .action(async ({ session }, dungeonName) => {
        if (!dungeonName) return '请输入副本名称'
        
        try {
          const dungeonInfo = await this.jx3Api.getDungeonInfo(dungeonName)
          return this.formatDungeonInfo(dungeonInfo)
        } catch (error) {
          ctx.logger.error('查询副本信息失败:', error)
          return `查询失败: ${error.message}`
        }
      })
    
    // 副本攻略
    ctx.command('jx3.攻略 <dungeonName>', '查询副本攻略')
      .action(async ({ session }, dungeonName) => {
        if (!dungeonName) return '请输入副本名称'
        
        try {
          // 获取副本信息
          const dungeonInfo = await this.jx3Api.getDungeonInfo(dungeonName)
          
          // 返回攻略链接或内容
          if (dungeonInfo.strategyUrl) {
            return `【${dungeonName}】攻略链接：${dungeonInfo.strategyUrl}`
          } else if (dungeonInfo.strategy) {
            return this.formatDungeonStrategy(dungeonInfo)
          } else {
            return `未找到【${dungeonName}】的攻略信息`
          }
        } catch (error) {
          ctx.logger.error('查询副本攻略失败:', error)
          return `查询失败: ${error.message}`
        }
      })
    
    // BOSS信息
    ctx.command('jx3.boss <bossName>', '查询副本BOSS信息')
      .action(async ({ session }, bossName) => {
        if (!bossName) return '请输入BOSS名称'
        
        try {
          // 尝试从副本信息中查找BOSS
          const allDungeons = await this.getAllDungeons()
          
          for (const dungeon of allDungeons) {
            const matchedBoss = dungeon.bosses.find(boss => 
              boss.name.includes(bossName) || bossName.includes(boss.name))
            
            if (matchedBoss) {
              return this.formatBossInfo(matchedBoss, dungeon.name)
            }
          }
          
          return `未找到BOSS【${bossName}】的信息`
        } catch (error) {
          ctx.logger.error('查询BOSS信息失败:', error)
          return `查询失败: ${error.message}`
        }
      })
    
    // 副本掉落查询
    ctx.command('jx3.掉落 <itemName>', '查询物品在哪个副本掉落')
      .action(async ({ session }, itemName) => {
        if (!itemName) return '请输入物品名称'
        
        try {
          // 遍历所有副本查找物品掉落
          const allDungeons = await this.getAllDungeons()
          const matchedDrops = []
          
          for (const dungeon of allDungeons) {
            for (const boss of dungeon.bosses) {
              const matchedItems = boss.drops.filter(item => 
                item.name.includes(itemName) || itemName.includes(item.name))
              
              if (matchedItems.length > 0) {
                matchedDrops.push({
                  dungeon: dungeon.name,
                  boss: boss.name,
                  items: matchedItems
                })
              }
            }
          }
          
          if (matchedDrops.length > 0) {
            return this.formatDropInfo(itemName, matchedDrops)
          } else {
            return `未找到物品【${itemName}】的掉落信息`
          }
        } catch (error) {
          ctx.logger.error('查询物品掉落失败:', error)
          return `查询失败: ${error.message}`
        }
      })
  }
  
  /**
   * @description 获取所有副本信息
   * @returns {Promise<Array>} 副本信息列表
   */
  async getAllDungeons() {
    // 这里应该从API获取所有副本列表
    // 由于我们没有具体的API，这里返回模拟数据
    return [
      {
        name: '冰火狮王',
        level: 90,
        type: '5人本',
        bosses: [
          {
            name: '冰狮子',
            skills: ['寒冰吐息', '冰刺地板', '冰龙卷'],
            drops: [
              { name: '寒冰项链', quality: '紫色', type: '饰品' }
            ]
          },
          {
            name: '火狮子',
            skills: ['烈焰喷射', '火焰地毯', '狮吼'],
            drops: [
              { name: '炽焰护腕', quality: '紫色', type: '护腕' }
            ]
          }
        ]
      },
      {
        name: '苍龙竞技场',
        level: 95,
        type: '10人本',
        bosses: [
          {
            name: '青龙',
            skills: ['龙息', '风暴', '龙之舞'],
            drops: [
              { name: '青龙刀', quality: '橙色', type: '武器' }
            ]
          }
        ]
      }
    ]
  }
  
  /**
   * @description 格式化副本信息
   * @param {object} dungeonInfo - 副本信息
   * @returns {string} 格式化后的副本信息
   */
  formatDungeonInfo(dungeonInfo) {
    const { name, level, type, minLevel, requiredScore, bosses, entranceMap, description } = dungeonInfo
    
    let info = `【副本】${name}
【类型】${type}
【等级】${level}级
${minLevel ? `【进入等级】${minLevel}级` : ''}
${requiredScore ? `【装备分要求】${requiredScore}` : ''}
${entranceMap ? `【入口位置】${entranceMap}` : ''}
${description ? `【描述】${description}` : ''}

【BOSS列表】`
    
    bosses.forEach((boss, index) => {
      info += `
${index + 1}. ${boss.name}`
    })
    
    return info
  }
  
  /**
   * @description 格式化副本攻略
   * @param {object} dungeonInfo - 副本信息
   * @returns {string} 格式化后的副本攻略
   */
  formatDungeonStrategy(dungeonInfo) {
    const { name, strategy, bosses } = dungeonInfo
    
    let strategyText = `【${name}】攻略：
${strategy}

`
    
    if (bosses && bosses.length > 0) {
      bosses.forEach(boss => {
        if (boss.strategy) {
          strategyText += `【${boss.name}】攻略：
${boss.strategy}

`
        }
      })
    }
    
    return strategyText
  }
  
  /**
   * @description 格式化BOSS信息
   * @param {object} bossInfo - BOSS信息
   * @param {string} dungeonName - 副本名称
   * @returns {string} 格式化后的BOSS信息
   */
  formatBossInfo(bossInfo, dungeonName) {
    const { name, skills, drops, hp, strategy } = bossInfo
    
    let info = `【BOSS】${name}
【副本】${dungeonName}
${hp ? `【生命值】${hp}` : ''}

【技能列表】`
    
    if (skills && skills.length > 0) {
      skills.forEach((skill, index) => {
        info += `
${index + 1}. ${typeof skill === 'string' ? skill : skill.name}${typeof skill !== 'string' && skill.description ? ` - ${skill.description}` : ''}`
      })
    } else {
      info += `
暂无技能信息`
    }
    
    info += `

【掉落物品】`
    
    if (drops && drops.length > 0) {
      drops.forEach((drop, index) => {
        info += `
${index + 1}. ${drop.name}${drop.quality ? ` (${drop.quality})` : ''}`
      })
    } else {
      info += `
暂无掉落信息`
    }
    
    if (strategy) {
      info += `

【攻略提示】
${strategy}`
    }
    
    return info
  }
  
  /**
   * @description 格式化物品掉落信息
   * @param {string} itemName - 物品名称
   * @param {Array} matchedDrops - 匹配的掉落信息
   * @returns {string} 格式化后的掉落信息
   */
  formatDropInfo(itemName, matchedDrops) {
    let info = `【${itemName}】掉落信息：

`
    
    matchedDrops.forEach((drop, index) => {
      info += `${index + 1}. 副本【${drop.dungeon}】 - BOSS【${drop.boss}】
`
      
      if (drop.items && drop.items.length > 0) {
        drop.items.forEach(item => {
          info += `   ${item.name}${item.quality ? ` (${item.quality})` : ''}${item.dropRate ? ` - 掉率${item.dropRate}` : ''}
`
        })
      }
      
      if (index < matchedDrops.length - 1) {
        info += `
`
      }
    })
    
    return info
  }
}

// 配置模式定义
const configSchema = Schema.object({})

// 插件主方法
module.exports.name = 'jx3-dungeon'
module.exports.inject = ['database', 'jx3Api']

module.exports.Config = configSchema

module.exports.apply = (ctx, config) => {
  // 创建插件实例
  ctx.plugin(Jx3DungeonPlugin, config)
  
  ctx.on('ready', () => {
    ctx.logger.info('剑网三副本信息查询插件已启动')
  })
} 